<script lang="ts">
import { defineComponent } from 'vue'

export default defineComponent({
  name: 'Page'
})
</script>

<template>
  <ContentWrap class="mobile-container">
    <!--    顶部查询项-->
    <el-form :model="form" inline class="mobile-form">
      <el-form-item label="退货退款单编号">
        <el-input
          v-model="form.returnorder_no"
          clearable
          placeholder="请输入退货退款单编号"
          style="width: 250px"
        />
      </el-form-item>
      <el-form-item label="客户">
        <el-input v-model="form.customer_name" clearable disabled style="width: 250px" />
        <el-button class="m-l-20px" size="small" type="primary" @click="handleOpenCustomer"
          >选择客户
        </el-button>
      </el-form-item>
      <el-form-item label="签订人">
        <el-select
          v-model="form.signatory"
          filterable
          placeholder="请选择签订人"
          clearable
          style="width: 200px"
        >
          <el-option
            v-for="item in operatorList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="签订日期">
        <el-date-picker
          v-model="form.date"
          type="daterange"
          format="YYYY/MM/DD"
          range-separator="-"
          start-placeholder="起始时间"
          end-placeholder="结束时间"
          @change="changeTime"
          :editable="false"
          unlink-panels
        />
      </el-form-item>
      <el-form-item label="退货原因">
        <el-select
          v-model="form.return_reason"
          filterable
          placeholder="请选择退货原因"
          clearable
          style="width: 200px"
        >
          <el-option
            v-for="item in reasonList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="initialize">查询</el-button>
        <el-button icon="Refresh" @click="reset">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 移动端卡片视图 -->
    <div v-if="isMobile" class="mobile-card">
      <el-card v-for="item in dataList" :key="item.id" class="goods-return-card">
        <template #header>
          <div class="card-header">
            <span class="order-no">{{ item.returnorder_no }}</span>
            <el-tag :type="getStatusTagType(item.status)" size="small">
              {{ useEnumeratePicker(statusList, item.status) }}
            </el-tag>
          </div>
        </template>

        <div class="card-content">
          <div class="info-row">
            <span class="label">客户:</span>
            <span class="value">{{ item.customer_name || '-' }}</span>
          </div>

          <div class="info-row">
            <span class="label">关联订单:</span>
            <span class="value">{{ item.order_no || '-' }}</span>
          </div>

          <div class="info-row">
            <span class="label">创建时间:</span>
            <span class="value">{{ item.create_time || '-' }}</span>
          </div>

          <div class="info-row">
            <span class="label">创建人:</span>
            <span class="value">{{ useEnumeratePicker(operatorList, item.creator) }}</span>
          </div>

          <div class="info-row">
            <span class="label">更新时间:</span>
            <span class="value">{{ item.update_time || '-' }}</span>
          </div>
        </div>

        <!-- 移动端操作按钮 -->
        <div class="card-actions">
          <el-button
            v-if="item.status === 2"
            type="primary"
            size="small"
            @click="handleWarehouse(item)"
            class="action-btn"
          >
            入库
          </el-button>
        </div>
      </el-card>
    </div>

    <!-- 桌面端表格视图 -->
    <div v-else class="mobile-table">
      <el-table
        :data="dataList"
        highlight-current-row
        stripe
        border
        v-loading="tableLoading"
        :cell-style="{ textAlign: 'center' }"
        :header-cell-style="{ textAlign: 'center' }"
      >
        <!-- 序号 -->
        <el-table-column label="序号" width="70">
          <template #default="{ row }">
            {{ row.id }}
          </template>
        </el-table-column>

        <!-- 退货退款单编号 -->
        <el-table-column
          :label="t('orderReturn.returnorder_no')"
          prop="returnorder_no"
          min-width="200"
          :show-overflow-tooltip="true"
        />

        <!-- 订单编号 -->
        <el-table-column
          :label="t('order.orderCode')"
          prop="order_no"
          min-width="160"
          :show-overflow-tooltip="true"
        />

        <!-- 订单序号 -->
        <el-table-column
          :label="t('order.order_id')"
          prop="order_id"
          min-width="120"
          :show-overflow-tooltip="true"
        />

        <!-- 客户 -->
        <el-table-column
          label="客户"
          prop="customer_name"
          min-width="150"
          :show-overflow-tooltip="true"
        />

        <!-- 关联订单 -->
        <el-table-column
          label="关联订单"
          prop="order_no"
          min-width="150"
          :show-overflow-tooltip="true"
        />

        <!-- 创建时间 -->
        <el-table-column
          label="创建时间"
          prop="create_time"
          min-width="180"
          :show-overflow-tooltip="true"
        />

        <!-- 创建人 -->
        <el-table-column
          label="创建人"
          prop="creator"
          min-width="120"
          :show-overflow-tooltip="true"
        >
          <template #default="{ row }">
            {{ useEnumeratePicker(operatorList, row.creator) }}
          </template>
        </el-table-column>

        <!-- 更新时间 -->
        <el-table-column
          label="更新时间"
          prop="update_time"
          min-width="180"
          :show-overflow-tooltip="true"
        />

        <!-- 操作 -->
        <el-table-column label="操作" min-width="120" fixed="right">
          <template #default="{ row }">
            <el-button
              v-if="row.status === 2"
              size="small"
              type="primary"
              @click="handleWarehouse(row)"
            >
              入库
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!--    分页-->
    <Pagination
      class="mobile-table"
      :total="paginationTotal"
      v-model:page="form.pageIndex"
      v-model:limit="form.pageSize"
      @pagination="initialize"
    />
  </ContentWrap>

  <DialogCustomerChecked
    ref="DialogCustomerCheckedRef"
    @expose-multiple-data="getExposeCustomerData"
    class="mobile-dialog"
  />
  <DialogWarehouse ref="DialogWarehouseRef" class="mobile-dialog" @refresh="initialize" />
</template>

<script setup lang="ts">
import dayjs from 'dayjs'
import Pagination from '@/components/Pagination/index.vue'
import { ContentWrap } from '@/components/ContentWrap'
import { getEnumApi, getReturnOrderListApi } from '@/api/orderReturn'
import { ElButton, ElMessage } from 'element-plus'
import { useClipboard } from '@vueuse/core'
import DialogCustomerChecked from '@/views/OrderReturn/OrderReturnManage/components/DialogCustomerChecked/index.vue'
import DialogWarehouse from './components/DialogWarehouse/index.vue'
import { useAppStore } from '@/store/modules/app'

const { copy } = useClipboard()
const { t } = useI18n()
const { push } = useRouter()
const appStore = useAppStore()

// 移动端检测
const isMobile = computed(() => appStore.getMobile)

const tableLoading = ref<boolean>(false)
const dataList = ref<any[]>([])
const DialogCustomerCheckedRef = ref()
const DialogWarehouseRef = ref()

// 获取状态标签类型
const getStatusTagType = (status: string | number) => {
  switch (status) {
    case 2:
      return 'warning' // 待入库
    case 3:
      return 'success' // 已入库
    default:
      return 'info'
  }
}

// 跳转到详情页
const handleJump = (type: string, row: any) => {
  push({
    path: `/orderReturn-management/goodsReturn/${type}`,
    query: { id: row.id }
  })
}

const paginationTotal = ref<number>(0)
const form = ref<Record<string, any>>({
  returnorder_no: '',
  customer_id: undefined,
  customer_name: '',
  return_reason: '',
  returnorder_type: '',
  signatory: undefined,
  min_total_amount: '',
  max_total_amount: '',
  min_paid_amount: '',
  max_paid_amount: '',
  date: '',
  signing_start_date: '',
  signing_end_date: '',
  pageIndex: 1,
  pageSize: 20
})

const modelList = ref<Array<Record<string, any>>>([])
const operatorList = ref<Array<Record<string, any>>>([])
const reasonList = ref<Array<Record<string, any>>>([])
const returnorderTypeList = ref<Array<Record<string, any>>>([])
const orderTypeList = ref<Array<Record<string, any>>>([])
const statusList = ref<Array<Record<string, any>>>([])

//格式化时间
const changeTime = (e: Date[]) => {
  if (e && e.length > 0) {
    form.value.signing_start_date = dayjs(e[0]).format('YYYY-MM-DD 00:00:00')
    form.value.signing_end_date = dayjs(e[1]).format('YYYY-MM-DD 23:59:59')
  } else {
    form.value.signing_start_date = null
    form.value.signing_end_date = null
  }
}

//入库
const handleWarehouse = (row: any) => {
  nextTick(() => {
    DialogWarehouseRef!.value!.open(row)
  })
}

//打开选择客户弹框
const handleOpenCustomer = () => {
  nextTick(() => {
    DialogCustomerCheckedRef!.value!.dialogVisible = true
    DialogCustomerCheckedRef!.value!.initialize(
      form.value.user_id ? [{ ...form.value, id: form.value.user_id }] : []
    )
  })
}

//接收勾选中的客户
const getExposeCustomerData = (val: any[]) => {
  if (!val || !val.length) return
  form.value.customer_id = val[0].id
  form.value.customer_name = val[0].cusname
}

//获取枚举
const getDropDownBoxInfo = async () => {
  const resp = await getEnumApi({ field: 'all' })
  modelList.value = resp.data.model
  operatorList.value = resp.data.operator
  reasonList.value = resp.data.return_reason
  returnorderTypeList.value = resp.data.returnorder_type
  orderTypeList.value = resp.data.order_type
  statusList.value = resp.data.status
}

//根据接口枚举匹配出中文名称
const useEnumeratePicker = (
  enumList: any[],
  field: string | number,
  key?: string,
  value?: string
) => {
  if (!enumList) return
  const matchItem =
    enumList.find((item: Record<string, any>) => item[value ?? 'value'] === field) || {}
  return matchItem[key ?? 'label'] || ''
}

//初始化请求
const initialize = async () => {
  tableLoading.value = true
  const params = JSON.parse(JSON.stringify(form.value))
  delete params.date
  const resp = await getReturnOrderListApi(params)
  dataList.value = resp.data.list
  paginationTotal.value = resp.data.total
  tableLoading.value = false
}

//重置查询项
const reset = () => {
  form.value = {
    returnorder_no: '',
    customer_id: undefined,
    customer_name: '',
    return_reason: '',
    returnorder_type: '',
    signatory: undefined,
    min_total_amount: '',
    max_total_amount: '',
    min_paid_amount: '',
    max_paid_amount: '',
    signing_start_date: '',
    signing_end_date: '',
    pageIndex: 1,
    pageSize: 20
  }
  paginationTotal.value = 0
  initialize()
}

onMounted(() => {
  getDropDownBoxInfo()
  initialize()
})
</script>

<style lang="less" scoped>
// 移动端卡片样式优化
.mobile-card {
  .goods-return-card {
    .el-card__body {
      padding: 16px;

      .info-row {
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        margin-bottom: 12px;
        line-height: 1.5;

        &:last-child {
          margin-bottom: 0;
        }

        .label {
          min-width: 90px;
          margin-right: 8px;
          font-weight: 500;
          color: #666;
          flex-shrink: 0;
        }

        .value {
          line-height: 1.4;
          color: #333;
          text-align: right;
          word-break: break-all;
          flex: 1;
        }
      }
    }

    .el-card__header {
      padding: 12px 16px;

      .card-header {
        display: flex;
        font-size: 14px;
        font-weight: 600;
        justify-content: space-between;
        align-items: center;

        .order-no {
          font-size: 14px;
          font-weight: 600;
          color: #333;
        }

        .el-tag {
          font-size: 12px;
        }
      }
    }

    //.card-actions {
    //  display: flex;
    //  padding-top: 16px;
    //  margin-top: 16px;
    //  border-top: 1px solid #f0f0f0;
    //  flex-direction: column;
    //  gap: 8px;
    //
    //  .action-btn {
    //    width: 100%;
    //    height: 40px;
    //    margin-bottom: 8px;
    //    font-size: 14px;
    //    border-radius: 6px;
    //
    //    &:last-child {
    //      margin-bottom: 0;
    //    }
    //  }
    //}
  }
}

// 按照OrderReturnManage/Page.vue的样式，确保按钮不换行
.mobile-form {
  @media (width <= 768px) {
    .el-form-item {
      display: flex !important;
      align-items: center !important;
      width: 100% !important;
      margin-bottom: 16px !important;

      .el-form-item__label {
        display: inline-block !important;
        width: 80px !important;
        max-width: none !important;
        min-width: 80px !important;
        margin-bottom: 0 !important;
        overflow: visible !important;
        text-align: left !important;
        text-overflow: unset !important;
        white-space: normal !important;
        flex-shrink: 0 !important;
      }

      .el-form-item__content {
        display: flex !important;
        width: calc(100% - 80px) !important;
        min-width: 0 !important;
        margin-left: 12px !important;
        flex: 1 !important;
        flex-wrap: nowrap !important;
        align-items: center !important;

        .el-input,
        .el-select,
        .el-date-picker {
          width: 100% !important;
          min-width: 0 !important;
        }

        .el-input-number {
          width: 102px !important;
          flex-shrink: 0 !important;
        }

        // 确保按钮不换行
        .el-button {
          margin-bottom: 0 !important;
          white-space: nowrap !important;
          flex-shrink: 0 !important;
        }

        // 修复查询和重置按钮的水平对齐
        .el-button + .el-button {
          margin-left: 8px !important;
        }

        // 强制按钮水平对齐
        .el-form-item:last-child {
          .el-form-item__content {
            display: flex !important;
            flex-flow: row nowrap !important;
            justify-content: flex-start !important;
            align-items: center !important;

            .el-button {
              margin-right: 8px !important;

              &:last-child {
                margin-right: 0 !important;
              }
            }
          }
        }
      }
    }
  }
}

// 强制修复移动端按钮水平对齐
:deep(.mobile-form) {
  @media (width <= 768px) {
    .el-form-item__content {
      display: flex !important;
      flex-wrap: nowrap !important;
      align-items: center !important;
      min-width: 0 !important;

      .el-button {
        min-width: fit-content !important;
        white-space: nowrap !important;
        flex-shrink: 0 !important;
      }

      .el-date-picker {
        min-width: 0 !important;
        overflow: visible !important;
      }
    }

    // 专门处理按钮组的水平对齐
    .el-form-item:last-child {
      .el-form-item__content {
        display: flex !important;
        flex-flow: row nowrap !important;
        justify-content: flex-start !important;
        align-items: center !important;

        .el-button {
          margin-right: 8px !important;

          &:last-child {
            margin-right: 0 !important;
          }
        }
      }
    }
  }
}

// 移动端样式，不影响WEB端
.mobile-container {
  @media (width <= 768px) {
    .el-form {
      .el-form-item {
        display: flex !important;
        align-items: center !important;
        width: 100% !important;
        margin-bottom: 16px !important;

        .el-form-item__label {
          display: inline-block !important;
          width: 80px !important;
          max-width: none !important;
          min-width: 80px !important;
          margin-bottom: 0 !important;
          overflow: visible !important;
          text-align: left !important;
          text-overflow: unset !important;
          white-space: normal !important;
          flex-shrink: 0 !important;
        }

        .el-form-item__content {
          display: flex !important;
          width: calc(100% - 80px) !important;
          min-width: 0 !important;
          margin-left: 12px !important;
          flex: 1 !important;
          flex-wrap: nowrap !important;
          align-items: center !important;

          .el-input,
          .el-select,
          .el-date-picker {
            width: 100% !important;
            min-width: 0 !important;
          }

          .el-input-number {
            width: 102px !important;
            flex-shrink: 0 !important;
          }

          // 确保按钮不换行
          .el-button {
            flex-shrink: 0 !important;
            white-space: nowrap !important;
          }
        }
      }
    }
  }
}
</style>
